package com.tequila.api.controller;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import com.tequila.domain.dto.wx.WxTicketDto;
import com.tequila.domain.dto.wx.WxTokenDto;
import fe.core.ApiResponse;
import fe.core.FastJson;
import fe.core.HttpClientUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * Created by fe on 2017/8/17.
 */
@RestController
@RequestMapping("/wx")
public class WxController {

    public static final Logger             logger              = LoggerFactory.getLogger(WxController.class);

    public static final String             APP_ID              = "wx99eff446127851a3";

    public static final String             APP_SECRET          = "274b1084b69c516da5ba34ed04a2de68";

    public static final String             WX_TOKEN_URL        = "https://api.weixin.qq.com/cgi-bin/token";

    public static ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(1);

    private static String                  WX_TOKEN_RESULT;

    private static String                  WX_TICKET;

    static {
        scheduledThreadPool.scheduleWithFixedDelay(() -> {
            String url = WX_TOKEN_URL + "?grant_type=client_credential&appid=" + APP_ID + "&secret=" + APP_SECRET;
            logger.info("wxToken request url : {}", url);
            WX_TOKEN_RESULT = HttpClientUtils.get(url);
            logger.info("wxToken response : {}", WX_TOKEN_RESULT);
        }, 0, 1, TimeUnit.HOURS);

        scheduledThreadPool.scheduleWithFixedDelay(() -> {
            WxTokenDto wxTokenDto = FastJson.fromJson(WX_TOKEN_RESULT, WxTokenDto.class);
            String ticketUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + wxTokenDto.getAccess_token() + "&type=jsapi";
            logger.info("wx ticket request url : {}", ticketUrl);
            String result = HttpClientUtils.get(ticketUrl);
            WxTicketDto wxTicketDto = FastJson.fromJson(result, WxTicketDto.class);
            WX_TICKET = wxTicketDto.getTicket();
            logger.info("wx ticket response : {}", WX_TICKET);
        }, 0, 1, TimeUnit.HOURS);

    }

    @RequestMapping("/auth")
    public void auth(HttpServletRequest request, HttpServletResponse response) {
        String echoStr = request.getParameter("echostr");
        logger.info("echoStr : {}", echoStr);
        try {
            response.addHeader("Content-Type", "text/plain");
            OutputStream outputStream = response.getOutputStream();
            IOUtils.write(echoStr, outputStream);
        } catch (Exception e) {
            logger.error("qrCode error ,e : {}", e);
        }
    }

    @RequestMapping("/wxToken")
    public ApiResponse wxToken() {
        return ApiResponse.successApiResponse().withData(WX_TOKEN_RESULT);
    }

    @RequestMapping("/getTicket")
    public ApiResponse getTicket(String token, String clientUrl) {

        String noncestr = RandomStringUtils.randomAlphanumeric(16);
        long timestamp = System.currentTimeMillis() / 1000;

        String signatureString = "jsapi_ticket=" + WX_TICKET + "&noncestr=" + noncestr + "&timestamp=" + timestamp + "&url=" + clientUrl;
        String signature = DigestUtils.sha1Hex(signatureString);

        Map<String, Object> ret = Maps.newHashMap();
        ret.put("jsapi_ticket", WX_TICKET);
        ret.put("noncestr", noncestr);
        ret.put("timestamp", timestamp);
        ret.put("signature", signature);
        ret.put("url", clientUrl);
        ret.put("appId", APP_ID);

        logger.info("签名串：{}", signatureString);
        logger.info("返回结果：{}", JSON.toJSONString(ret));
        return ApiResponse.successApiResponse().withData(ret);
    }

}
